import axios from 'axios'
import router from '../router'

export const baseUrl=process.env.NODE_ENV === 'production'
    ? localStorage.baseUrl
    : '/api/loaner/'
let http = axios.create({
  baseURL: baseUrl,
  withCredentials: true,
  headers: {
    'Content-Type': 'application/json;charset=utf-8',
  }
})
// 响应拦截器
let isExpired=true
http.interceptors.response.use(
  response => {
    if(response.config.method=='post'){
      if (response.data.code == 999 && isExpired) {
        isExpired=!isExpired
        alert(response.data.msg)
        setTimeout(()=>{
          router.push('/')
        },1000)
      }
      if(response.data.code == 500){
        alert(response.data.msg)
        return
      }
      if(response.data.code=='000000'){
        return response.data.data
      }
    }else{
      return response.data.data
    }
  }  
)
export const get=(url,params)=>{
  return new Promise((resolve,reject) => {
    http({
      method:"GET",
      url:url,
      params:params,
    }).then(response => {
      resolve(response);
    },err => {
      reject(err)
    })
 })
}
export const post=(url,data)=>{
  return new Promise((resolve,reject) => {
    http({
      method:"POST",
      url:url,
      data:data,
    }).then(response => {
      resolve(response);
    },err => {
      reject(err)
    })
 })
}
export const buildTree=(arr,id)=>{
  let temp = {}
  let tree = {}
  // 数组转 键值对
  arr.forEach(item => {
    temp[item[id]] = item
  })
  let keys = Object.keys(temp)
  keys.forEach(key => {
    // 获取当前项
    let item = temp[key]
    // 当前项 pId
    let pid = item.parentId
    // 获取父级项
    let pidItem = temp[pid]
    if (pidItem) {
      if (!pidItem.children) {
        pidItem.children = []
      }
      pidItem.children.push(item)
    } else {
      tree[item[id]] = item
    }
  })
  // 对象转数组并返回
  return Object.keys(tree).map(key => tree[key])
}
export default axios